﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class CustomerManagement_DiscountAlterationManagementDetail : System.Web.UI.Page
{
    TextBox txtNote;
    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataSet DstDetails
    {
        get
        {
            DataSet dstDetails = null;
            if (ViewState["DstDetails"] != null)
            {
                dstDetails = (DataSet)ViewState["DstDetails"];
            }
            return dstDetails;
        }
        set
        {
            ViewState["DstDetails"] = value;
        }
    }

    private bool IsAudit
    {
        get
        {
            bool isAudit = false;
            if (ViewState["IsAudit"] != null)
            {
                isAudit = Convert.ToBoolean(ViewState["IsAudit"]);
            }
            return isAudit;
        }
        set
        {
            ViewState["IsAudit"] = value;
        }
    }

    private List<Model.V_CARSET> Cards
    {
        get
        {
            List<Model.V_CARSET> cards = null;
            if (ViewState["Cards"] != null)
            {
                cards = (List<Model.V_CARSET>)ViewState["Cards"];
            }
            return cards;
        }
        set
        {
            ViewState["Cards"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("300400101");
        if (!IsPostBack)
        {
            BindMain();
            BindDetails();
            if (this.IsAudit)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
            }
        }

        Session["FCode"] = "300400101";
    }

    private void BindMain()
    {
        DataSet dst = new BLL.DISCADJUST().GetMainById(this.Code);
        if (dst.Tables[0].Rows.Count > 0)
        {
            this.IsAudit = dst.Tables[0].Rows[0]["DA_CHECK"].ToString() == "1" ? true : false;
        }
        dlistMain.DataSource = dst;
        dlistMain.DataBind();
    }

    private void BindDetails()
    {
        this.DstDetails = new BLL.DISCADJUSTDETAIL().GetDetailsById(this.Code);
        dlistDetail.DataSource = this.DstDetails;
        dlistDetail.DataBind();
    }

    protected void dlistDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            if (this.DstDetails != null)
            {
                this.DstDetails.Tables[0].Rows.RemoveAt(e.Item.ItemIndex);
                dlistDetail.DataSource = this.DstDetails;
                dlistDetail.DataBind();
            }
        }
    }
    protected void dlistDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            DropDownList dropOriginalLevel = (DropDownList)e.Item.FindControl("dropOriginalLevel");
            DropDownList dropRegulateLevel = (DropDownList)e.Item.FindControl("dropRegulateLevel");
            if (dropOriginalLevel != null)
            {
                BindDropCardLevel(dropOriginalLevel);
                for (int i = 0; i < dropOriginalLevel.Items.Count; i++)
                {
                    if (dropOriginalLevel.Items[i].Value == this.DstDetails.Tables[0].Rows[e.Item.ItemIndex]["OriginalLevel"].ToString())
                    {
                        dropOriginalLevel.SelectedIndex = i;
                        break;
                    }
                }
            }

            if (dropRegulateLevel != null)
            {
                BindDropCardLevel(dropRegulateLevel);
                for (int i = 0; i < dropRegulateLevel.Items.Count; i++)
                {
                    if (dropRegulateLevel.Items[i].Value == this.DstDetails.Tables[0].Rows[e.Item.ItemIndex]["RegulateLevel"].ToString())
                    {
                        dropRegulateLevel.SelectedIndex = i;
                        break;
                    }
                }
            }
            if (this.IsAudit)
            {
                dropRegulateLevel.Enabled = false;
                ((TextBox)e.Item.FindControl("txtRegulateDiscount")).Enabled = false;
                ((TextBox)e.Item.FindControl("txtNote")).Enabled = false;
                ((Button)e.Item.FindControl("btnDelete")).Enabled = false;
            }
        }
    }

    private void BindDropCardLevel(DropDownList drop)
    {
        if (this.Cards == null)
        {
            this.Cards = new BLL.V_CARSET().GetAllList();
        }

        drop.DataSource = this.Cards;
        drop.DataTextField = "MC";
        drop.DataValueField = "DM";
        drop.DataBind();
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400101", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.DISCADJUST da = new BLL.DISCADJUST().GetModel(this.Code);
            if (da != null)
            {
                if (da.DA_CHECK==1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            SetValueOfDataTable(this.DstDetails);
            if (this.DstDetails.Tables[0].Rows.Count == 0)
            {
                Share.InsertLog("300400101", "00017");
                throw new Exception("请选择您要调整的会员！");
            }
            if (new BLL.DISCADJUST().Save(this.Code, this.DstDetails,((TextBox)dlistMain.Items[0].FindControl("txtNote")).Text))
            {
                Share.Alert(this.Page, "保存成功！");
            }
            else
            {
                Share.Alert(this.Page, "保存失败，请重新尝试保存！");
            }

        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    protected void btnAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("300400101", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.DISCADJUST da = new BLL.DISCADJUST().GetModel(this.Code);
            if (da != null)
            {
                if (da.DA_CHECK == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            DataSet dstDetails = new BLL.DISCADJUSTDETAIL().GetDetails(this.Code);

            if (dstDetails.Tables[0].Rows.Count == 0)
            {
                throw new Exception("请添加要调整的会员！");
            }

            StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
            StringBuilder strSqlToUpdateErpDB = new StringBuilder();
            char[] charToTrim = new char[] { '|' };

            string strCommandOfBStyle;
            string strCommandOfErp;
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            string[] strArraySqlCommandArrayToUpdateBStyleDB;
            string[] strArraySqlCommandArrayToUpdateErpDB;

            for (int i = 0; i < dstDetails.Tables[0].Rows.Count; i++)
            {
                

                strSqlToUpdateBStyleDB.Append("update v_vipset set KLDM='");
                strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["DAD_ALEVEL"].ToString());
                strSqlToUpdateBStyleDB.Append("',ZK=");
                strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["DAD_ADISC"].ToString());
                strSqlToUpdateBStyleDB.Append(" where DM='");
                strSqlToUpdateBStyleDB.Append(dstDetails.Tables[0].Rows[i]["DM"].ToString());
                strSqlToUpdateBStyleDB.Append("'|");

                strSqlToUpdateErpDB.Append("update v_vipset set KLDM='");
                strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["DAD_ALEVEL"].ToString());
                strSqlToUpdateErpDB.Append("',ZK=");
                strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["DAD_ADISC"].ToString());
                strSqlToUpdateErpDB.Append(" where DM='");
                strSqlToUpdateErpDB.Append(dstDetails.Tables[0].Rows[i]["DM"].ToString());
                strSqlToUpdateErpDB.Append("'|");
            }
            for (int i = 0; i < dlistMain.Items.Count; i++)
            {
                txtNote = (TextBox)dlistMain.Items[i].FindControl("txtNote");
            }
            strSqlToUpdateBStyleDB.Append("update DISCADJUST set DA_CHECK=1,DA_CHECKER='");
            strSqlToUpdateBStyleDB.Append(Share.UserValue(0));
            strSqlToUpdateBStyleDB.Append("',DA_CHECKDATE='");
            strSqlToUpdateBStyleDB.Append(DateTime.Now);
             strSqlToUpdateBStyleDB.Append("',DA_NOTE='");
             strSqlToUpdateBStyleDB.Append(txtNote.Text.Trim());
            strSqlToUpdateBStyleDB.Append("' where DA_ID='");
            strSqlToUpdateBStyleDB.Append(this.Code);
            strSqlToUpdateBStyleDB.Append("'|");

            strCommandOfBStyle = strSqlToUpdateBStyleDB.ToString();
            strCommandOfErp = strSqlToUpdateErpDB.ToString();

            strArraySqlCommandArrayToUpdateBStyleDB = strCommandOfBStyle.TrimEnd(charToTrim).Split(charToTrim);
            strArraySqlCommandArrayToUpdateErpDB = strCommandOfErp.TrimEnd(charToTrim).Split(charToTrim);

            LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();

            //bool result = new SQLServerDAL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(strArraySqlCommandArrayToUpdateErpDB);

            bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, strArraySqlCommandArrayToUpdateBStyleDB, strArraySqlCommandArrayToUpdateErpDB);
            if (result)
            {
                btnAudit.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnAddDetail.Enabled = false;
                BindMain();
                BindDetails();

                Share.InsertLog("300400101", "00010");
                Share.Alert(this.Page, "审核成功！");
            }
            else
            {
                Share.Alert(this.Page, "审核失败，请重新审核！");
            }
           
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Check.CheckPermission("300400101", "00003"))
            {
                Share.Alert(this.Page, "无权操作"); return;
            }
            Model.DISCADJUST da = new BLL.DISCADJUST().GetModel(this.Code);
            if (da != null)
            {
                if (da.DA_CHECK == 1)
                {
                    throw new Exception("此单据已被审核，不允许再次操作！");
                }
            }
            bool result = new BLL.DISCADJUST().Delete(this.Code);
            if (result)
            {
                Share.InsertLog("300400101", "00003");
                Response.Write("<script>alert('删除成功！');window.location.href='DiscountAlterationManagement.aspx'</script>");
            }
            else
            {
                Response.Write("<script>alert('删除失败！');</script>");
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("DiscountAlterationManagementDetail.aspx?code=" + this.Code);
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("DiscountAlterationManagement.aspx");
    }

    protected void btnAddDetail_Click(object sender, EventArgs e)
    {
        try
        {
            string customerCode = hidUserCode.Value;
            SetValueOfDataTable(this.DstDetails);
            if (customerCode != "")
            {
                string[] customersArray = customerCode.Split('|');
                if (customersArray.Length > 0)
                {
                    string[] customer;
                    for (int i = 0; i < customersArray.Length; i++)
                    {
                        customer = customersArray[i].Split(' ');
                        if (customer.Length == 2)
                        {


                            Model.V_VIPSET customerInfo = new BLL.V_VIPSET().GetModel(customer[0]);
                            if (customerInfo == null)
                            {
                                throw new Exception("无法获取会员原始折扣信息！");
                            }
                            if (this.Cards == null)
                            {
                                this.Cards = new BLL.V_CARSET().GetAllList();
                            }
                            this.DstDetails = new BLL.DISCADJUSTDETAIL().AddDataRowToDataTable(this.DstDetails, Convert.ToString(this.DstDetails.Tables[0].Rows.Count + 1), customer[0], customer[1], customerInfo.KLDM, customerInfo.ZK, this.Cards[0].DM, this.Cards[0].ZK);

                        }
                    }
                    dlistDetail.DataSource = this.DstDetails;
                    dlistDetail.DataBind();
                }
            }
            else
            {
                return;//Share.Alert(this.Page, "请选择会员！");
            }
            hidUserCode.Value = "";
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    private void SetValueOfDataTable(DataSet dst)
    {
        Label lblDetailId;
        Label lblCustomerCode;
        Label lblCustomerName;
        DropDownList dropOriginalLevel;
        Label lblOriginalDiscount;
        DropDownList dropRegulateLevel;
        TextBox txtRegulateDiscount;
        TextBox txtNote;

        for (int i = 0; i < dlistDetail.Items.Count; i++)
        {
            lblDetailId = (Label)dlistDetail.Items[i].FindControl("lblDetailId");
            lblCustomerCode = (Label)dlistDetail.Items[i].FindControl("lblCustomerCode");
            lblCustomerName = (Label)dlistDetail.Items[i].FindControl("lblCustomerName");
            dropOriginalLevel = (DropDownList)dlistDetail.Items[i].FindControl("dropOriginalLevel");
            lblOriginalDiscount = (Label)dlistDetail.Items[i].FindControl("lblOriginalDiscount");
            dropRegulateLevel = (DropDownList)dlistDetail.Items[i].FindControl("dropRegulateLevel");
            txtRegulateDiscount = (TextBox)dlistDetail.Items[i].FindControl("txtRegulateDiscount");
            txtNote = (TextBox)dlistDetail.Items[i].FindControl("txtNote");

            dst.Tables[0].Rows[i]["DAD_DETAILCODE"] = lblDetailId.Text;
            dst.Tables[0].Rows[i]["DAD_CUSTOMERCODE"] = lblCustomerCode.Text;
            dst.Tables[0].Rows[i]["GKMC"] = lblCustomerName.Text;
            dst.Tables[0].Rows[i]["OriginalLevel"] = dropOriginalLevel.SelectedValue;
            dst.Tables[0].Rows[i]["OriginalDiscount"] = lblOriginalDiscount.Text;
            dst.Tables[0].Rows[i]["RegulateLevel"] = dropRegulateLevel.SelectedValue;
            dst.Tables[0].Rows[i]["RegulateDiscount"] = Convert.ToDecimal(txtRegulateDiscount.Text.Trim());
            dst.Tables[0].Rows[i]["DAD_NOTE"] = txtNote.Text.Trim();
        }

    }

    protected void DataList2_DDLCHANGE_Click(object sender, EventArgs e)
    {
        DropDownList dropRegulateLevel = (DropDownList)sender;
        TextBox txtRegulateDiscount = (TextBox)dropRegulateLevel.Parent.FindControl("txtRegulateDiscount");
        foreach (Model.V_CARSET temp in this.Cards)
        {
            if (dropRegulateLevel.SelectedValue == temp.DM)
            {
                txtRegulateDiscount.Text = String.Format("{0:0.00}", temp.ZK);
                break;
            }
        }
    }
}
